#include <Arduino.h>
#include "ArduinoJson.h"
#include "ESP8266WiFi.h"

const char *WifiName = "Xiaomi 14";
const char *WifiPassword = "147258369";

const char *host = "api.seniverse.com";
const int httpPort = 80;

String reqUserKey = "SCcAOhN3wlgZ_fS0W";
String reqLocation = "Xiamen";
String reqUnit = "c";

String reqRes = "/v3/weather/now.json?key=" + reqUserKey +
                +"&location=" + reqLocation +
                "&language=en&unit=" + reqUnit;

void parseInfo(WiFiClient client)
{
    const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + 2 * JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 230;
    DynamicJsonDocument doc(capacity);

    deserializeJson(doc, client);

    JsonObject results_0 = doc["results"][0];

    JsonObject results_0_now = results_0["now"];

    // Serial.printf("@Code");
    // Serial.println(results_0_now["code"].as<int>());
    // // 43 6F 64 65 20 31 33 0D 0A
    Serial.printf("@Code %d \r\n", results_0_now["code"].as<int>());
    delay(500);
    Serial.printf("@Temperature %d\r\n", results_0_now["temperature"].as<int>());
}

void httpRequest(String reqRes)
{
    WiFiClient client;

    // 建立http请求信息
    String httpRequest = String("GET ") + reqRes + " HTTP/1.1\r\n" +
                         "Host: " + host + "\r\n" +
                         "Connection: close\r\n\r\n";
    // 尝试连接服务器
    if (client.connect(host, 80))
    {
        // 向服务器发送http请求信息
        client.print(httpRequest);

        // 获取并显示服务器响应状态行
        String status_response = client.readStringUntil('\n');

        // 使用find跳过HTTP响应头
        if (client.find("\r\n\r\n"))
        {
            // Serial.println("Found Header End. Start Parsing.");
        }

        // 利用ArduinoJson库解析心知天气响应信息
        parseInfo(client);
    }
    else
    {
        Serial.println(" connection failed!");
    }
    // 断开客户端与服务器连接工作
    client.stop();
}

void connectWifi(const char *WifiName, const char *WifiPassword, uint8_t WaitTime)
{
    WiFi.mode(WIFI_STA);

    WiFi.disconnect();

    WiFi.begin(WifiName, WifiPassword);
    uint8_t count = 0;
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        // Serial.println("connect WiFi...");
        if (count >= WaitTime)
        {
            Serial.println("connect WiFi fail");
            return;
        }
    }
    Serial.printf("@connect WIFI success\r\n");
    // Serial.printf("local IP is %s\r\n", WiFi.localIP().toString().c_str());
    Serial.printf("@Name %s\r\n", WiFi.SSID().c_str());
    delay(500);
    Serial.printf("@IP %s\r\n", WiFi.localIP().toString().c_str());
}

void setup()
{
    Serial.begin(115200);
    connectWifi(WifiName, WifiPassword, 15);
}

void loop()
{
    if (WiFi.status() != WL_CONNECTED)
    {
        Serial.printf("WiFi is broken");
        connectWifi(WifiName, WifiPassword, 15);
    }
    httpRequest(reqRes);
    delay(500);
    Serial.printf("@connect WIFI success\r\n");
    delay(500);
    Serial.printf("@Name %s\r\n", WiFi.SSID().c_str());
    delay(500);
    Serial.printf("@IP %s\r\n", WiFi.localIP().toString().c_str());
    delay(1500);
}
